<template>
  <div class="approval-list">
    <!-- 搜索区域 -->
    <div class="search-area">
      <a-form layout="inline">
        <a-form-item label="申请人">
          <a-tree-select v-model="searchForm.applicant_id" show-search treeNodeFilterProp="title" style="width:140px"
            :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }" :tree-data="personListTree" placeholder="请选择申请人">
          </a-tree-select>
        </a-form-item>
        <a-form-item label="审批状态">
          <a-select v-model="searchForm.status" placeholder="审批状态" allowClear @change="handleSearch"
            style="width: 120px">
            <a-select-option value="pending">待提交</a-select-option>
            <a-select-option value="processing">审批中</a-select-option>
            <a-select-option value="approved">已通过</a-select-option>
            <a-select-option value="rejected">已拒绝</a-select-option>
            <a-select-option value="withdrawn">已撤回</a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="提交日期">
          <a-range-picker v-model="dateRange" @change="handleDateChange" :placeholder="['开始日期', '结束日期']" />
        </a-form-item>

        <a-form-item>
          <a-button type="primary" @click="handleSearch">
            查询
          </a-button>
          <a-button style="margin-left: 8px" @click="handleReset">
            重置
          </a-button>
        </a-form-item>
      </a-form>
    </div>

    <!-- 表格区域 -->
    <div class="table-area">
      <vxe-table ref="xTable" :loading="loading" :data="tableData" :auto-resize="true" :height="tableHeight" resizable
        show-overflow="tooltip">
        <!-- <vxe-column type="checkbox" title="" width="60"></vxe-column> -->
        <vxe-column field="application_id" title="ID" width="60" />
        <vxe-column field="title" title="报题" min-width="120" show-overflow="tooltip" />
        <vxe-column field="applicant_name" title="申请人" width="160"></vxe-column>
        <vxe-column field="status" title="审批状态" width="100">
          <template v-slot="{ row }">
            <a-tag :color="getStatusColor(row.status)">
              {{ getStatusText(row.status) }}
            </a-tag>
          </template>
        </vxe-column>
        <vxe-column field="created_at" title="提交时间" width="160">
          <template v-slot="{ row }">
            {{ formatDate(row.created_at) }}
          </template>
        </vxe-column>
        <vxe-column field="content" title="内容" min-width="240" show-overflow="tooltip" />
        <vxe-column field="output_types" title="产出类型" min-width="150">
          <template v-slot="{ row }">
            <a-space>
              <a-tag v-for="(item,index) in row.output_types_arr" :key="index" :color="getOutputTypeColor(item)">
                {{ item }}</a-tag>
            </a-space>
          </template>
        </vxe-column>
        <vxe-column title="操作" width="60" align="center">
          <template v-slot="{ row }">
            <a-button type="link" size="small" @click="handleGetDetail(row)">
              详情
            </a-button>
          </template>
        </vxe-column>
      </vxe-table>

      <!-- 分页 -->
      <!-- <vxe-pager
        :current-page="page.current"
        :page-size="page.size"
        :total="page.total"
        :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'FullJump', 'Sizes', 'Total']"
        @page-change="handlePageChange"
      /> -->

      <div class="pagination-container">
        <a-pagination v-model="page.current" :total="page.total" :page-size="page.size"
          :page-size-options="['10', '20', '30', '40']" show-size-changer show-quick-jumper
          :show-total="total => `共 ${total} 条记录`" @change="handlePageChange" @showSizeChange="handleSizeChange" />
      </div>

      <!-- 详情 -->
      <a-modal v-model="detailVisible" title="报题详情" :footer="null" width="90%">
        <a-row :gutter="64">
          <a-col class="gutter-row" :span="8" v-if="detailVisible">
            <h2 style="font-weight:bold">报题内容</h2>
            <a-form ref="form" layout="horizontal" :label-col="{ span: 4 }" :wrapper-col="{ span: 18 }">
              <a-form-item label="报题名称">
                <span>{{detailRow.title}}</span>
              </a-form-item>

              <a-form-item label="工作成员">
                <a-space>
                  <a-tag v-for="item in detailRow.work_members_name" :key="item.person_id">{{ item.person_name }}
                  </a-tag>
                </a-space>
              </a-form-item>

              <a-form-item label="产出类型">
                <a-space>
                  <a-tag v-for="item in detailRow.outputs" :key="item.application_id"
                    :color="getOutputTypeColor(item.type)">
                    {{ item.type }}</a-tag>
                </a-space>
              </a-form-item>

              <a-form-item label="预计工期">
                <a-space>
                  <span>{{formatDate(detailRow.estimated_start_date)}}</span>
                  <span>-</span>
                  <span>{{formatDate(detailRow.estimated_end_date)}}</span>
                </a-space>
              </a-form-item>

              <a-form-item label="报题内容">
                <span>{{detailRow.content}}</span>
              </a-form-item>

              <a-form-item label="提交时间">
                <span>{{formatDateTime(detailRow.created_at)}}</span>
              </a-form-item>
            </a-form>
          </a-col>
          <a-col class="gutter-row" :span="6">
            <h2 style="font-weight:bold">审批流程</h2>
            <a-timeline class="a-timeline-content" style="margin-top:64px">
              <!-- 发起 -->
              <a-timeline-item>
                <a-space>
                  <a-avatar style="backgroundColor:#1890ff;" :size="64">{{detailRow.applicant_name}}</a-avatar>
                  <span><strong>{{detailRow.applicant_name}}</strong> 发起</span>
                </a-space>
              </a-timeline-item>
              <!-- 一级 二级 -->
              <a-timeline-item v-for="item in detailRow.flows_records" :key="item.flow_id"
                :color="getStatusColor(item.status)">
                <a-space>
                  <a-avatar style="backgroundColor:#1890ff;" :size="64">{{item.approver_name}}</a-avatar>
                  <div>
                    <span><strong>{{item.approver_name}}</strong> {{item.level}}级审批</span>&nbsp;&nbsp;
                    <a-tag :color="getFlowStatusColor(item.status)">{{getFlowStatusText(item.status)}}</a-tag>
                    <div v-if="item.records[0]">{{formatDateTime(item.records[0].approved_at)}}</div>
                    <div v-if="item.records[0]">{{(item.records[0].comment)}}</div>
                  </div>
                </a-space>
              </a-timeline-item>
            </a-timeline>
          </a-col>
          <a-col class="gutter-row" :span="10">
            <h2 style="font-weight:bold">产出详情</h2>
            <div class="output-content" v-for="item in detailRow.outputs" :key="item.attachment_id">
              <a-form style="width:50%;" ref="form" layout="horizontal" :label-col="{ span: 8 }"
                :wrapper-col="{ span: 16 }">
                <a-form-item label="产出类型">
                  <a-tag :color="getOutputTypeColor(item.type)">{{item.type}}</a-tag>
                </a-form-item>

                <a-form-item label="上传时间">
                  <a-space>
                    <span>{{formatDateTime(item.updated_at)}}</span>
                  </a-space>
                </a-form-item>

                <a-form-item label="上传人">
                  <a-space>
                    <span>{{item.uploaded_by_name}}</span>
                  </a-space>
                </a-form-item>

                <a-form-item label="状态">
                  <a-tag :color="getOutputStatusColor(item.status)">{{getOutputStatusText(item.status)}}</a-tag>
                </a-form-item>


                <a-form-item label="描述">
                  <a-space>
                    <span>{{(item.description)}}</span>
                  </a-space>
                </a-form-item>
              </a-form>
              <!-- <div class="output-pic"> -->
              <el-image v-if="item.file_url" class="output-pic" fit="cover" :src="item.file_url"
                :preview-src-list="[item.file_url]" />
              <!-- </div> -->
            </div>
          </a-col>
        </a-row>
      </a-modal>
    </div>
  </div>
</template>

<script>
  import {
    apiApprovalList,
    apiApprovalGetById,
    apiPersonGetAllListTree,
  } from '@/api/featch'
  import moment from 'moment'

  export default {
    name: 'ApprovalList',
    data() {
      return {
        moment, // 添加到data中
        // 搜索表单
        searchForm: {
          applicant_id: undefined,
          status: undefined,
          start_date: undefined,
          end_date: undefined
        },

        personListTree: [],

        // 日期范围
        dateRange: [],

        // 表格数据
        tableData: [],
        loading: false,
        tableHeight: null,

        // 分页信息
        page: {
          current: 1,
          size: 10,
          total: 0
        },

        detailVisible: false,
        detailRow: {},
        detailLoading: false
      }
    },
    computed: {

    },
    mounted() {
      this.searchForm.approved_status = this.$route.params.approved_status
      this.initTableHeight()
      this.getInitialPersonListTree()
      this.getTableData()

      // 监听窗口大小变化
      window.addEventListener('resize', this.initTableHeight)
    },
    beforeDestroy() {
      window.removeEventListener('resize', this.initTableHeight)
    },
    methods: {
      /**
       * @description 获取初始人员列表 树状
       */
      async getInitialPersonListTree() {
        this.personLoading = true
        try {
          const res = await apiPersonGetAllListTree({})
          if (res.code === 200) {
            this.personListTree = [...res.data]
          } else {
            this.$message.error(res.message)
          }
        } catch (err) {
          this.$message.error(err.toString())
        }
        this.personLoading = false
      },
      /**
       * @description 格式化日期
       */
      formatDate(date) {
        if (!date) return '-'
        return this.moment(date).format('YYYY-MM-DD')
      },
      /**
       * @description 格式化日期时间
       */
      formatDateTime(date) {
        if (!date) return '-'
        return this.moment(date).format('YYYY-MM-DD HH:mm:ss')
      },
      /**
       * @description 获取状态文字 审批实例
       */
      getStatusText(status) {
        const statusMap = {
          'pending': '待提交',
          'processing': '审批中',
          'approved': '已通过',
          'rejected': '已拒绝',
          'withdrawn': '已撤回',
        }
        return statusMap[status] || '未知'
      },
      /**
       * @description 获取状态颜色 审批实例
       */
      getStatusColor(status) {
        const colorMap = {
          'pending': 'gray',
          'processing': 'orange',
          'approved': 'green',
          'rejected': 'red',
          'withdrawn': 'cyan',
        }
        return colorMap[status] || 'default'
      },
      /**
       * @description 获取状态文字 节点
       */
      getFlowStatusText(status) {
        const statusMap = {
          'pending': '待审批',
          'approved': '已通过',
          'rejected': '已拒绝',
        }
        return statusMap[status] || '未知'
      },
      /**
       * @description 获取状态颜色 节点
       */
      getFlowStatusColor(status) {
        const colorMap = {
          'pending': 'orange',
          'approved': 'green',
          'rejected': 'red',
        }
        return colorMap[status] || 'default'
      },
      /**
       * @description 获取产出类型颜色
       */
      getOutputTypeColor(status) {
        const colorMap = {
          '新媒体图文': 'purple',
          '新媒体视频': 'green',
          '广播电视类': 'blue',
        }
        return colorMap[status] || 'default'
      },
      /**
       * @description 获取状态文字 产出类型
       */
      getOutputStatusText(status) {
        const statusMap = {
          'pending': '待上传',
          'completed': '已完成',
        }
        return statusMap[status] || '未知'
      },
      /**
       * @description 获取状态颜色 产出类型
       */
      getOutputStatusColor(status) {
        const statusMap = {
          'pending': 'orange',
          'completed': 'blue',
        }
        return statusMap[status] || '未知'
      },
      /**
       * @description 处理日期变化
       */
      handleDateChange(dates) {
        if (dates && dates.length === 2) {
          this.searchForm.start_date = dates[0].format('YYYY-MM-DD')
          this.searchForm.end_date = dates[1].format('YYYY-MM-DD')
        } else {
          this.searchForm.start_date = undefined
          this.searchForm.end_date = undefined
        }
        this.handleSearch()
      },

      /**
       * @description 初始化表格高度
       */
      initTableHeight() {
        const clientHeight = document.documentElement.clientHeight
        this.tableHeight = clientHeight - 64 - 48 - 132 - 44
      },

      /**
       * @description 获取表格数据
       */
      async getTableData() {
        this.loading = true
        try {
          const params = {
            page: this.page.current,
            page_size: this.page.size,
            applicant_id: this.searchForm.applicant_id,
            status: this.searchForm.status,
            start_date: this.searchForm.start_date,
            end_date: this.searchForm.end_date
          }
          const res = await apiApprovalList(params)
          if (res.code === 200) {
            res.data.list.map(item => {
              item.output_types_arr = item.output_types.split(",")
            })
            console.log(res.data.list)
            this.tableData = res.data.list || []
            this.page.total = res.data.pagination.total || 0

            // 如果当前页没有数据且不是第一页，则跳转到上一页
            if (this.tableData.length === 0 && this.page.current > 1) {
              this.page.current--
              this.getTableData()
            }
          } else {
            this.$message.error(res.message)
          }
        } catch (err) {
          this.$message.error(err.toString())
        }
        this.loading = false
      },
      /**
       * @description 处理搜索
       */
      handleSearch() {
        this.page.current = 1
        this.getTableData()
      },
      /**
       * @description 重置搜索
       */
      handleReset() {
        this.searchForm = {
          applicant_id: undefined,
          approved_status: undefined,
          start_date: undefined,
          end_date: undefined
        }
        this.dateRange = []
        this.handleSearch()
      },
      /**
       * @description 处理分页变化
       */
      handlePageChange(page) {
        this.page.current = page
        this.getTableData()
      },
      /**
       * @description 每页条数改变
       */
      handleSizeChange(current, size) {
        this.page.current = 1
        this.page.size = size
        this.getTableData()
      },
      /**
       * @description 获取详情
       */
      handleGetDetail(row) {
        this.detailLoading = true
        apiApprovalGetById({
          application_id: row.application_id
        }).then(res => {
          this.detailLoading = false
          if (res.code === 200) {
            this.detailRow = res.data
            this.detailVisible = true
          } else {
            this.$message.error(res.message)
          }
        }).catch(err => {
          this.detailLoading = false
          this.$message.error(err.toString())
        })
      }
    }
  }
</script>

<style lang="less" scoped>
  .approval-list {
    height: 100%;

    .search-area {
      padding: 24px 24px 16px 24px;
      background: #fff;
      border-radius: 4px;
    }

    .table-area {
      background: #fff;
      padding: 0 24px;
      border-radius: 4px;

      .pagination-container {
        margin-top: 16px;
        text-align: right;
      }
    }
  }

  .a-timeline-content {
    /deep/ .ant-timeline-item-content {
      transform: translateY(-24px);
      margin-left: 32px;
    }
  }

  .output-content {
    display: flex;
    margin-bottom: 24px;

    .output-pic {
      margin-left: 24px;
      width: 256px;
      height: 256px;

      .avatar-uploader>.ant-upload {
        width: 256px;
        height: 256px;
      }

      .ant-upload-select-picture-card i {
        font-size: 32px;
        color: #999;
      }

      .ant-upload-select-picture-card .ant-upload-text {
        margin-top: 8px;
        color: #666;
      }

      /deep/ .ant-upload.ant-upload-select-picture-card {
        width: 256px !important;
        height: 256px !important;
      }

      .avatar-uploader img {
        width: 256px;
        height: 256px;
        object-fit: cover;
      }

      // /deep/ .el-image__inner {
      //   width: 100%;
      //   height: 100%;
      // }
    }
  }
</style>